package org.jaaksi.demo.ptr.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.squareup.picasso.Picasso;
import java.util.List;

/**
 * Created by Fcy
 * 列表页基类，修改集成BaseAdapter，添加addAll,clear等直接通过adapter操作数据源
 */
public abstract class BaseListAdapter<D> extends BaseAdapter {

  protected Picasso mPicasso;
  private List<D> mInfos;
  private final Object mLock = new Object();

  protected LayoutInflater mInflater;
  protected Context mContext;

  public BaseListAdapter(Context context) {
    mPicasso = Picasso.with(context);
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.mContext = context;
  }

  public Context getContext() {
    return mContext;
  }

  public int getCount() {
    return isEmpty() ? 0 : mInfos.size();
  }

  public D getItem(int position) {
    return isEmpty() ? null : mInfos.get(position);
  }

  public long getItemId(int position) {
    return position;
  }

  public abstract View getView(int position, View convertView, ViewGroup parent);

  public void setDatas(List<D> infos) {
    mInfos = infos;
    notifyDataSetChanged();
  }

  public List<D> getDatas() {
    return mInfos;
  }

  public boolean isEmpty() {
    return mInfos == null;
  }

  public void add(D t) {
    synchronized (mLock) {
      if (isEmpty()) {
        return;
      }
      mInfos.add(t);
    }
  }

  public void addAll(List<D> list) {
    synchronized (mLock) {
      if (isEmpty()) {
        return;
      }
      if (list != null) {
        mInfos.addAll(list);
      }
    }
  }

  public void clear() {
    if (isEmpty()) {
      return;
    }
    synchronized (mLock) {
      mInfos.clear();
    }
  }

  @SuppressWarnings("unchecked")
  protected static <T extends View> T findViewById(View view, int id) {
    return (T) view.findViewById(id);
  }
}
